package com.xiaolong.shiro;

import java.io.Serializable;
import java.util.Deque;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.DefaultSessionKey;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;

import com.google.common.collect.Lists;
import com.xiaolong.model.SysUser;

public class KickoutSessionControlFilter extends AccessControlFilter {

	private String kickoutUrl;
	private boolean kickoutAfter = false;
	private int maxSession = 1;
	
	private SessionManager sessionManager;
	private Cache<String,Deque<Serializable>> cache;
	
	public void setKickoutUrl(String kickoutUrl) {
		this.kickoutUrl = kickoutUrl;
	}

	public void setKickoutAfter(boolean kickoutAfter) {
		this.kickoutAfter = kickoutAfter;
	}

	public void setMaxSession(int maxSession) {
		this.maxSession = maxSession;
	}

	public void setSessionManager(SessionManager sessionManager) {
		this.sessionManager = sessionManager;
	}

	public void setCacheManager(CacheManager cacheManager) {
        this.cache = cacheManager.getCache("shiro-kickout-session");
    }

	@Override
	protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue)
			throws Exception {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
		Subject subject = getSubject(request, response);
		if(!subject.isAuthenticated()&& !subject.isRemembered()){
			//如果没有登陆 跳出流程
			return true;
		}
		Session session = subject.getSession();
		SysUser user = (SysUser) subject.getPrincipal();
		Serializable sessionId = session.getId();
		
		//同步控制
		Deque<Serializable> deque = cache.get(user.getUsername());
		if(deque==null){
			deque = Lists.newLinkedList();
			cache.put(user.getUsername(), deque);
		}
		
		//如果队列里的sessionId数超出最大会话数，开始踢人
		if(!deque.contains(sessionId)&&session.getAttribute("kickout")==null){
			deque.push(sessionId);
		}
		
		while(deque.size()>maxSession){
			Serializable kickoutSessionId = null;
			if(kickoutAfter){
				kickoutSessionId = deque.removeLast();
			}else{
				kickoutSessionId = deque.removeFirst();
			}
			
			Session kickoutSession = sessionManager.getSession(new DefaultSessionKey(kickoutSessionId));
			if(kickoutSession != null){
				kickoutSession.setAttribute("kickout", true);
			}
		}
		
		if(session.getAttribute("kickout")!=null){
			subject.logout();
			saveRequest(request);
			WebUtils.issueRedirect(request, response, kickoutUrl);
			return false;
		}
		return true;
	}

}
